package com.nuanshui.heatedloan.userinfo.service;

import com.alibaba.fastjson.JSON;
import com.nuanshui.heatedloan.baseservice.service.CommonServiceImpl;
//import com.nuanshui.heatedloan.baseservice.rongyun.RongyunFacade;
//import com.nuanshui.heatedloan.baseservice.rongyun.models.FormatType;
//import com.nuanshui.heatedloan.baseservice.rongyun.models.SdkHttpResult;
import com.nuanshui.framework.cache.CacheConstants;
import com.nuanshui.framework.exception.BizException;
import com.nuanshui.framework.exception.GlobalErrorCode;
import com.nuanshui.framework.lang.DateUtil;
import com.nuanshui.framework.lang.SysStringUtils;
import com.nuanshui.framework.res.ResourceFacade;
import com.nuanshui.framework.utils.redis.JedisUtil;
import com.nuanshui.heatedloan.constant.GlobalParam;
import com.nuanshui.heatedloan.userinfo.facade.UserIntegralService;
import com.nuanshui.heatedloan.userinfo.facade.UserQueryService;
import com.nuanshui.heatedloan.userinfo.facade.UserService;
import com.nuanshui.heatedloan.userinfo.facade.UserTokenService;
import com.nuanshui.heatedloan.userinfo.model.*;
import com.nuanshui.heatedloan.userinfo.tool.UserTool;
import com.nuanshui.heatedloan.userinfo.vo.IncrUserIntegralVo;
import com.nuanshui.heatedloan.userinfo.vo.UserIntegralVo;
import org.apache.commons.beanutils.BeanUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.lang.reflect.InvocationTargetException;
import java.util.Calendar;
import java.util.List;

@Component("userTool")
public class UserToolImpl extends CommonServiceImpl implements UserTool {

    @Autowired
    private JedisUtil jedisUtil;
    @Autowired
    private UserService userService;

    @Autowired
    private UserQueryService userQueryService;

    @Autowired
    private ResourceFacade resourceFacade;

    @Autowired
    private UserIntegralService userIntegralService;
    @Autowired
    private UserTokenService userTokenService;
    //@Autowired
    //private RongyunFacade rongyunFacade;

    protected Logger log = LoggerFactory.getLogger(getClass());

    /**
     * 增加用户积分
     *
     * @return
     */
    @Override
    public IncrUserIntegralVo incrUserIntegral(String userId, String... actions) {
        double score = 0d;
        IncrUserIntegralVo incrUserIntegralVo = new IncrUserIntegralVo();
        if (userId == null) return incrUserIntegralVo;
        if (actions != null) {
            boolean showAlertMsg = false;
            for (String action : actions) {
                try {
                    jedisUtil.clock(action);
                    IntegralAction integralAction = jedisUtil.hget(CacheConstants.INTEGRAL_ACTION_MAP, action, IntegralAction.class);
                    if (integralAction == null) continue;
                    showAlertMsg = showAlertMsg || integralAction.isAlertMsg(userId);
                    if (integralAction.isIncr(userId)) {
                        if (showAlertMsg) {
                            incrUserIntegralVo.setMsg(integralAction.getAlertMsg());
                        }
                        score += integralAction.getScore();
                        UserIntegral userIntegral = new UserIntegral();
                        userIntegral.setActionCode(integralAction.getActionCode());
                        userIntegral.setUserId(userId);
                        userIntegral.setScore(integralAction.getScore());
                        Calendar calendar = Calendar.getInstance();
                        if (integralAction.getNumOfDay() == 1) {
                            calendar.add(Calendar.DAY_OF_MONTH, -1);
                            userIntegral.setDate(DateUtil.format(calendar.getTime(), "yyyy-MM-dd"));
                        } else {
                            userIntegral.setDate(DateUtil.getToday("yyyy-MM-dd"));
                        }
                        //
                        saveScoreToUser(userIntegral);
                        jedisUtil.hset(CacheConstants.INTEGRAL_ACTION_MAP, action, integralAction);
                    }
                } finally {
                    jedisUtil.unclock(action);
                }
            }
            incrUserIntegralVo.setScore((int) score);
            incrUserIntegralVo.setShowAlertMsg(showAlertMsg);

            //获取升级问题
            SimpleUserInfo simpleUserInfo = getSimpleUserInfo(userId);
            int oldLevel = parseUserLevel(simpleUserInfo.getScore());
            simpleUserInfo.setScore(simpleUserInfo.getScore() + score);
            jedisUtil.setObject(GlobalParam.USER_PREFIX + userId, simpleUserInfo);
            int level = parseUserLevel(simpleUserInfo.getScore());
            incrUserIntegralVo.setLevel(level);
            incrUserIntegralVo.setOldLevel(oldLevel);
            return incrUserIntegralVo;
        } else {
            return new IncrUserIntegralVo();
        }


    }

    /**
     * 增加用户积分
     *
     * @return
     */
    @Override
    public IncrUserIntegralVo incrUserIntegral(String userId, String action) {
        double score = 0d;
        IncrUserIntegralVo incrUserIntegralVo = new IncrUserIntegralVo();
        String key = userId;
        if (userId.contains("_")) {
            userId = userId.substring(0, userId.indexOf("_"));
        }
        if (userId == null) return incrUserIntegralVo;
        boolean showAlertMsg = false;
        try {
            jedisUtil.clock(action);
            IntegralAction integralAction = jedisUtil.hget(CacheConstants.INTEGRAL_ACTION_MAP, action, IntegralAction.class);
            if (integralAction == null) return incrUserIntegralVo;
            showAlertMsg = showAlertMsg || integralAction.isAlertMsg(userId);
            if (integralAction.isIncr(key)) {
                if (showAlertMsg) {
                    incrUserIntegralVo.setMsg(integralAction.getAlertMsg());
                }
                score += integralAction.getScore();
                UserIntegral userIntegral = new UserIntegral();
                userIntegral.setActionCode(integralAction.getActionCode());
                userIntegral.setUserId(userId);
                userIntegral.setScore(integralAction.getScore());
                Calendar calendar = Calendar.getInstance();
                if (integralAction.getNumOfDay() == 1) {
                    calendar.add(Calendar.DAY_OF_MONTH, -1);
                    userIntegral.setDate(DateUtil.format(calendar.getTime(), "yyyy-MM-dd"));
                } else {
                    userIntegral.setDate(DateUtil.getToday("yyyy-MM-dd"));
                }
                saveScoreToUser(userIntegral);
                jedisUtil.hset(CacheConstants.INTEGRAL_ACTION_MAP, action, integralAction);
            }
        } finally {
            jedisUtil.unclock(action);
        }
        incrUserIntegralVo.setScore((int) score);
        incrUserIntegralVo.setShowAlertMsg(showAlertMsg);

        //获取升级问题
        SimpleUserInfo simpleUserInfo = getSimpleUserInfo(userId);
        int oldLevel = parseUserLevel(simpleUserInfo.getScore());
        simpleUserInfo.setScore(simpleUserInfo.getScore() + score);
        jedisUtil.setObject(GlobalParam.USER_PREFIX + userId, simpleUserInfo);
        int level = parseUserLevel(simpleUserInfo.getScore());
        incrUserIntegralVo.setLevel(level);
        incrUserIntegralVo.setOldLevel(oldLevel);
        return incrUserIntegralVo;
    }

    /**
     * 获取用户基本信息
     *
     * @return
     */
    @Override
    public SimpleUserInfo getSimpleUserInfo(String userId) {
        if (StringUtils.isEmpty(userId)) return null;
        SimpleUserInfo userInfo = jedisUtil.getObject(GlobalParam.USER_PREFIX + userId, SimpleUserInfo.class);
        if (userInfo != null && userInfo.getAuth() == 0) {
            userInfo = null;
        }
        if (userInfo != null) return userInfo;
        UserInfo user = userQueryService.loadUserInfo(userId);
        if (user == null) return new SimpleUserInfo();
        userInfo = new SimpleUserInfo();
        userInfo.setId(user.getId());
        userInfo.setAvatarUrl(resourceFacade.resolveUrl(user.getAvatar()));
        userInfo.setLocation(user.getLocation());
        userInfo.setNick(user.getNick());
        userInfo.setVerified(user.getVerified());
        userInfo.setScore(user.getScore());
        userInfo.setAuth(user.getAuth());
        userInfo.setVerifiedType(user.getVerifiedType());
        userInfo.setAvatar(user.getAvatar());
        userInfo.setPhone(user.getPhone());
        jedisUtil.setObject(GlobalParam.USER_PREFIX + userId, userInfo);
        return userInfo;
    }

    /**
     * 获取用户基本信息
     *
     * @return
     */
    @Override
    public SimpleUserInfo setSimpleUserInfo(SimpleUserInfo userInfo) {
        jedisUtil.setObject(GlobalParam.USER_PREFIX + userInfo.getId(), userInfo);
        return userInfo;
    }

    /**
     * 删除缓存的用户信息
     *
     * @param userId
     */
    @Override
    public void deleteSimpleUserInfo(String userId) {
        jedisUtil.del(GlobalParam.USER_PREFIX + userId);
    }

    /**
     * 判断是否还可以加分
     *
     * @return
     */
    @Override
    public boolean isIncrUserIntegral(String action) {
        String userId = getCurrentUser().getId();
        IntegralAction integralAction = jedisUtil.hget(CacheConstants.INTEGRAL_ACTION_MAP, action, IntegralAction.class);
        if (integralAction == null) return false;
        return !integralAction.isNotIncr(userId);

    }

    @Override
    public List<IntegralRank> findAllIntegralRank() {
        List<IntegralRank> integralRanks = jedisUtil.lrangeAllObj(CacheConstants.USER_LEVEL_LIST, IntegralRank.class);
        if (integralRanks == null || integralRanks.size() <= 0) {
            synchronized (UserTool.class) {
                integralRanks = jedisUtil.lrangeAllObj(CacheConstants.USER_LEVEL_LIST, IntegralRank.class);
                if (integralRanks == null || integralRanks.size() <= 0) {
                    integralRanks = userIntegralService.findAllIntegralRank();
                    jedisUtil.del(CacheConstants.USER_LEVEL_LIST);
                    jedisUtil.rpush(CacheConstants.USER_LEVEL_LIST, integralRanks);
                }
            }
        }
        return integralRanks;
    }

    /**
     * 解析用户等级
     *
     * @param score
     * @return
     */
    @Override
    public int parseUserLevel(Double score) {
        if (score == null) return 0;
        List<IntegralRank> integralRanks = findAllIntegralRank();
        for (int i = 0; i < integralRanks.size(); i++) {
            IntegralRank integralRank = integralRanks.get(i);
            Double max = integralRank.getMaxScore();
            Double min = integralRank.getMinScore();
            if (score < max && score >= min) {
                return i;
            }
        }
        return 0;
    }

    /**
     * 获取用户等级
     *
     * @param userIntegralVo
     */
    @Override
    public void parseUserLevel(UserIntegralVo userIntegralVo) {
        if (userIntegralVo.getScore() == null) return;
        Double score = userIntegralVo.getScore();
        List<IntegralRank> integralRanks = findAllIntegralRank();
        if (integralRanks.size() <= 0) return;
        userIntegralVo.setMaxScore(integralRanks.get(integralRanks.size() - 1).getMaxScore());
        for (int i = 0; i < integralRanks.size(); i++) {
            IntegralRank integralRank = integralRanks.get(i);
            Double max = integralRank.getMaxScore();
            Double min = integralRank.getMinScore();
            if (score < max && score >= min) {
                userIntegralVo.setNeedScore(max - score);
                userIntegralVo.setLevel(i + 1);
                userIntegralVo.setLevelName(integralRank.getName());
                break;
            }

        }
    }


    /**
     * 获取当前用户信息
     * 如果是未登录的匿名用户，系统根据匿名用户唯一码自动创建一个用户
     * 具体逻辑查看：UniqueNoFilter
     * 获取当前用户
     *
     * @return
     */
    @Override
    public User getCurrentUser() {
        User user=getInternalUser();
        if(user!=null && !SysStringUtils.isNullOrEmpty(user.getId()))
        {
            return user;
        }
        throw new BizException(GlobalErrorCode.UNAUTHORIZED, "need login first.");
    }

    private User getInternalUser()
    {
        String strUserInfo = getCurrentUserInfo();
        if (SysStringUtils.isNotEmpty(strUserInfo)) {
            User user=JSON.parseObject(strUserInfo, User.class);
            return user;
        }
        return null;
    }

    /**
     * 获取当前用户信息
     * 如果是未登录的匿名用户，系统根据匿名用户唯一码自动创建一个用户
     * 具体逻辑查看：UniqueNoFilter
     *
     * @return
     */
    @Override
    public User getCurrentUserNotCheck() {

        User user=getInternalUser();
        if(user!=null && !SysStringUtils.isNullOrEmpty(user.getId()))
        {
            return user;
        }

        User empty = new User();
        empty.setId(null);
        return empty;
    }

    @Override
    public User getCurrentUserNotCheckEmptyId() {
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        if (auth != null) {
            Object principal = auth.getPrincipal();
            if (principal instanceof User) {
                User user = (User) principal;
                if (user != null && !user.isAnonymous()) {
                    return user;
                }
            }

            if (auth.getClass().getSimpleName().indexOf("Anonymous") < 0) {
                log.error("Unknown authentication encountered, ignore it. " + auth);
            }
        }

        User empty = new User();
        empty.setId("");
        return empty;
    }


    @Override
    public boolean isLoginUser() {

        try {
            Authentication auth = SecurityContextHolder.getContext().getAuthentication();
            if (auth != null) {
                Object principal = auth.getPrincipal();
                if (principal != null && principal instanceof User) {
                    User user = (User) principal;
                    if (user != null && !user.isAnonymous()) {
                        return true;
                    }
                }
            }
        } catch (Exception e) {
        }

        return false;
    }

    @Override
    public String getUserId() {

        return getCurrentUser().getId();
    }

    @Override
    public void updateChatToken(User user) {
//        try {
//            SdkHttpResult result = rongyunFacade.getToken(user.getId(), user.getNick(), resourceFacade.resolveUrl(user.getAvatar(), 180), FormatType.json);
//            if (result.getHttpCode() == 200) {
//                String token = JSON.parseObject(result.getResult()).getString("token");
//                user.setChatToken(token);
//                User u = new User();
//                u.setChatToken(token);
//                u.setId(user.getId());
//                userService.updateUserInfo(u, false);
//            }
//
//        } catch (Exception e) {
//            log.error("获取私信token失败", e);
//        }
    }

    private void saveScoreToUser(final UserIntegral userIntegral) {
        userIntegralService.save(userIntegral);
    }

	@Override
	public List<String> getUserIds(String nick) {
		return userService.getUserIds(nick);
	}

}
